import { onMounted, ref, isRef } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

export default function (props) {
  const { url, params = {}, formatResult, onSuccess, immediate = false } = props
  const loading = ref(false)
  const dataSource = ref([])
  const getData = async () => {
    loading.value = true
    const paramsData = isRef(params) ? params.value : params
    const { code, data, msg } = await post(url, paramsData)
    loading.value = false
    if (code !== 0) {
      dataSource.value = []
      message.error(msg || '请求失败')
      return
    }
    dataSource.value = formatResult ? formatResult(data) : data
    onSuccess && onSuccess(data)
  }

  onMounted(() => immediate && getData())

  return { loading, dataSource, getData }
}
